package com.sdkj.fixed.asset.assets.service;

import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.ScrapExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseBase;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.AssetLog;
import com.sdkj.fixed.asset.pojo.assets.Scrap;
import com.sdkj.fixed.asset.pojo.assets.ScrapAssets;
import com.sdkj.fixed.asset.pojo.assets.Warehouse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author niuliwei
 * @description 清理报废
 * @date 2020/7/27 9:33
 */
@Service
public class ScrapService extends BaseService<Scrap> {

    @Autowired
    private ScrapMapper scrapMapper;
    @Autowired
    private ScrapAssetsMapper scrapAssetsMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Override
    public BaseMapper getMapper() {
        return scrapMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }

    /**
     * 清理报废-新增
     * @param scrap
     * @return
     */
    public Scrap add(ScrapExtend scrap){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        scrap.setNumber(getNumber("QL", orgId));
        scrap.setDate(scrap.getDate());
        scrap.setScrapUser(scrap.getScrapUser());
        scrap.setIsDeleted(0);
        scrap.setCreateUser(userId);
        scrap.setCreateDate(TimeTool.getCurrentTimeStr());
        scrap.setUpdateUser(userId);
        scrap.setUpdateDate(TimeTool.getCurrentTimeStr());
        scrap.setOrgId(orgId);
        scrapMapper.insertSelective(scrap);

        historyMapper.batchInsert(scrap.getAssetIdList() ,scrap.getId(),8);

        for (String str : scrap.getAssetIdList()) {
            ScrapAssets asset = new ScrapAssets();
            asset.setScrapId(scrap.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());
            scrapAssetsMapper.insertSelective(asset);

            if("盘点管理".equals(scrap.getReserved())){
                stateLog(str, "盘点管理", "清理报废", scrap.getScrapUser(), userId);
            }else{
                stateLog(str, "清理报废", "清理报废", scrap.getScrapUser(), userId);
            }

        }

        scrapMapper.delInv(userId, orgId, scrap.getAssetIdList());

        //修改资产状为清理报废
        warehouseService.updateAssetState(scrap.getAssetIdList(), "清理报废", "", "");

        return scrap;
    }

    /**
     * 清理报废-分页查询
     * @param param
     * @return
     */
    public List<ScrapExtend> getAllPage(PageParams<SelPrams> param){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<ScrapExtend> list = scrapMapper.getScrap(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId, null);
        if(list != null && list.size()>0){
            for (ScrapExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),8);
                List<WarehouseBase> listBase = new ArrayList<>();
                results.stream().forEach(w->{
                    WarehouseBase base = new WarehouseBase();
                    BeanUtils.copyProperties(w, base);
                    listBase.add(base);
                });
                extend.setResults(listBase);
            }
        }

        return list;
    }

    /**
     * 清理报废-还原
     * @param id
     */
    public void reduction(String id){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        Example example = new Example(Scrap.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(id.split(",")));

        Scrap scrap = new Scrap();
        scrap.setIsDeleted(1);
        scrap.setRestoreUser(userId);
        scrap.setRestoreDate(TimeTool.getCurrentTimeStr());
        scrap.setUpdateUser(userId);
        scrap.setUpdateUser(TimeTool.getCurrentTimeStr());
        scrapMapper.updateByExampleSelective(scrap, example);

        List<String> ids = scrapMapper.getScrapAssetId(Arrays.asList(id.split(",")));
        ids.stream().forEach(e->{
            stateLog(e, "还原", "闲置", userName, userId);
        });

        Example example1 = new Example(ScrapAssets.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andIn("scrapId",  Arrays.asList(id.split(",")));
        ScrapAssets scrapAssets = new ScrapAssets();
        scrapAssets.setIsDeleted(1);
        scrapAssetsMapper.updateByExampleSelective(scrapAssets, example1);

        //修改资产状为闲置
        warehouseService.updateAssetState(ids, "闲置", "", "");
    }

    /**
     * 清理报废-查看详情
     * @return
     */
    public ScrapExtend selById(String id){
        ScrapExtend extend = scrapMapper.selById(id);
        List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),8);
        List<WarehouseBase> listBase = new ArrayList<>();
        results.stream().forEach(w->{
            WarehouseBase base = new WarehouseBase();
            BeanUtils.copyProperties(w, base);
            listBase.add(base);
        });
        extend.setResults(listBase);
        return extend;
    }

    /**
     * 清理报废-导出
     * @param startDate
     * @param endDate
     * @return
     */
    public List<ScrapExtend> exportExcel(String startDate, String endDate, String orgId, String token){
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<ScrapExtend> list = scrapMapper.getScrap(startDate, endDate, orgId, userId, null);
        if(list != null && list.size()>0){
            for (ScrapExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),8);
                List<WarehouseBase> listBase = new ArrayList<>();
                results.stream().forEach(w->{
                    WarehouseBase base = new WarehouseBase();
                    BeanUtils.copyProperties(w, base);
                    listBase.add(base);
                });
                extend.setResults(listBase);
            }
        }
        return list;
    }

    /**
     * 资产处理日志
     * @param assetId
     * @param modelName
     * @param afterState
     * @param handlerUser
     * @param handlerUserId
     */
    public void stateLog(String assetId, String modelName, String afterState, String handlerUser, String handlerUserId){
        Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);
        String logContent = "资产【"+warehouse.getAssetName()+"】"+ modelName +"处置；"
                +ChangLogUtil.simpleLogContxt(new LogContext(warehouse.getState(), afterState));
        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType(modelName);
        assetLog.setHandlerId(handlerUserId);
        assetLog.setHandlerUser(handlerUser);
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(handlerUserId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }
}
